package com.ly.heart.service.king.base;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.heart.domain.*;
import com.ly.heart.domain.king.BaseChildBo;
import com.ly.heart.domain.king.base.businessGroup.BusinessGroupBo;
import com.ly.heart.domain.king.base.businessGroup.BusinessGroupFEntityBo;
import com.ly.heart.domain.king.order.FConfirmerIdBo;
import com.ly.heart.domain.request.KingBaseSingleRequest;
import com.ly.heart.domain.response.KingBaseResponse;
import com.ly.heart.service.IKingBaseBusinessGroupService;
import com.ly.heart.service.IKingOrgService;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.heart.util.KingCommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 业务组推送Service
 */
@Component
@Slf4j
public class BusinessGroupPushService {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat ( "yyyy-MM-dd" );

    @Resource
    private IKingBaseBusinessGroupService businessGroupService;
    @Resource
    private IKingOrgService iKingOrgService;



    @Transactional( rollbackFor = Exception.class )
    public void push(String businessGroupId){
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity>().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity::getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        KingBaseBusinessGroupEntity businessGroupEntity = businessGroupService.selectKingBaseBusinessGroupEntityById(businessGroupId);
        if(Objects.isNull(businessGroupEntity)){
            throw new CustomException("业务组不存在！");
        }
        if(businessGroupEntity.getIsSend() == KingConstUtil.KING_DATA_IS_SEND_YES){
            throw new CustomException("该业务组已推送金蝶,无需重复推送！");
        }
        try {
            K3CloudApi client = new K3CloudApi (identifyInfo);
            save(businessGroupEntity,client);
//            submit(businessGroupEntity.getDocCode(),client);
//            audit(businessGroupEntity.getDocCode(),client);
            updateSendSuccess(businessGroupId);
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException("推送业务组失败！");
        }
    }

    private void updateSendSuccess(String businessGroupId){
        KingBaseBusinessGroupEntity businessGroupEntity = new KingBaseBusinessGroupEntity();
        businessGroupEntity.setId(businessGroupId);
        businessGroupEntity.setIsSend(KingConstUtil.KING_DATA_IS_SEND_YES);
        businessGroupEntity.setChangeTime(DateUtils.getNowDate());
        businessGroupEntity.setChangeId(SecurityUtils.getLoginUser().getUser().getUserId());
        boolean flag = businessGroupService.updateById(businessGroupEntity);
        if(!flag){
            throw new CustomException("修改推送状态失败！");
        }
    }


    public void save(KingBaseBusinessGroupEntity businessGroupEntity, K3CloudApi client){
        try {
            String formId = KingConstUtil.BD_OPERATORGROUPBILL;
            KingBaseSingleRequest singleRequest = new KingBaseSingleRequest ();
            BusinessGroupBo businessGroupBo = this.assembleBusinessGroup(businessGroupEntity);
            singleRequest.setModel(businessGroupBo);
            //调用接口
            String resultJson = client.save(formId, JSONObject.toJSONString(singleRequest));
            //用于记录结果
            Gson gson = new Gson();
            //对返回结果进行解析和校验
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
            if (baseResponse.getIsSuccess()) {
                log.info("业务组推送成功: {}", gson.toJson(repoRet.getResult()));
            } else {
                log.error("业务组推送失败: " + gson.toJson(repoRet.getResult().getResponseStatus()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

//    public void submit(String docCode, K3CloudApi client){
//        try{
//            OrderSubmitBo submitBo = new OrderSubmitBo();
//            List<String> numbers = new ArrayList<>();
//            numbers.add(docCode);
//            submitBo.setNumbers(numbers);
//            String formId = KingConstUtil.BD_OPERATORGROUPBILL;
//            String resultJson = client.submit(formId, JSON.toJSONString ( submitBo ));
//            Gson gson = new Gson();
//            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
//            KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
//            if (baseResponse.getIsSuccess()) {
//                log.info("业务组提交成功: {}", gson.toJson(repoRet.getResult()));
//            } else {
//                log.error("业务组提交失败: {}",gson.toJson(repoRet.getResult().getResponseStatus()));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    public void audit(String docCode,K3CloudApi client){
//        try{
//            OrderAuditBo auditBo = new OrderAuditBo();
//            List<String> numbers = new ArrayList<>();
//            numbers.add(docCode);
//            auditBo.setNumbers(numbers);
//            String formId = KingConstUtil.BD_OPERATORGROUPBILL;
//            String resultJson = client.audit(formId,JSON.toJSONString ( auditBo ));
//            Gson gson = new Gson();
//            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
//            KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
//            if (baseResponse.getIsSuccess()) {
//                log.info("业务组审核成功:{}", gson.toJson(repoRet.getResult()));
//            } else {
//                log.error("业务组审核失败:{}",gson.toJson(repoRet.getResult().getResponseStatus()) );
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }



    /**
     * 业务组推送金蝶对象
     * @param businessGroupEntity
     * @return supplierBo
     */
    private BusinessGroupBo assembleBusinessGroup(KingBaseBusinessGroupEntity businessGroupEntity){
        BusinessGroupBo businessGroupBo = new BusinessGroupBo();
        //创建日期
        businessGroupBo.setFCreateDate(dateFormat.format(businessGroupEntity.getCreateTime()));
        //修改人
        FConfirmerIdBo FModifierId = new FConfirmerIdBo().setFUserID(businessGroupEntity.getChangeId());
        businessGroupBo.setFModifierId(FModifierId);
        //修改日期
        if(Objects.nonNull(businessGroupEntity.getChangeTime())){
            businessGroupBo.setFModifyDate(dateFormat.format(businessGroupEntity.getChangeTime()));
        }
        //创建人
        FConfirmerIdBo FCreatorId = new FConfirmerIdBo().setFUserID(businessGroupEntity.getUserId());
        businessGroupBo.setFCreatorId(FCreatorId);
        //单据编号
        businessGroupBo.setFBillNo(businessGroupEntity.getDocCode());
        //业务组类型
        businessGroupBo.setFOperatorGroupType(businessGroupEntity.getBusinessGroupType());
        //描述
        businessGroupBo.setFDescription(businessGroupEntity.getDescInfo());
        //明细信息
        List<BusinessGroupFEntityBo> FEntity = new ArrayList<>();
        if(!CollectionUtils.isEmpty(businessGroupEntity.getBusinessGroupDetailList())){
            List<KingBaseBusinessGroupDetailEntity> groupDetailList = businessGroupEntity.getBusinessGroupDetailList();
            for(KingBaseBusinessGroupDetailEntity groupDetail : groupDetailList){
                BusinessGroupFEntityBo fEntityBo = new BusinessGroupFEntityBo();
                //业务组织
                BaseChildBo FBizOrgId = new BaseChildBo().setFNumber(KingConstUtil.DEFAULT_ORG);
                fEntityBo.setFBizOrgId(FBizOrgId);
                //编码
                fEntityBo.setFNumber(groupDetail.getBusinessCode());
                //业务组名称
                fEntityBo.setFName(groupDetail.getBusinessName());
                //业务组类型
                fEntityBo.setFOperatorGroupType_EYR(businessGroupEntity.getBusinessGroupType());
//                //是否启用
//                fEntityBo.setFIsUse(businessGroupEntity.getIsDisabled() == 1 ? true:false);
                //描述
                fEntityBo.setFdescription_ETY(groupDetail.getDescribeInfo());
                FEntity.add(fEntityBo);
            }
        }
        businessGroupBo.setFEntity(FEntity);
        return businessGroupBo;
    }






}
